/*
 * TextEncoder.c
 *
 *  Created on: 2012. 5. 8.
 *      Author: yjpark
 */

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "Protocol.h"

// text field delimiter
static char DELIMITER = '|';

// complete
size_t Text_Encode(char *tMsgs, uint8_t *outBuf, size_t bufSize) {

	uint8_t *bufPtr = outBuf;
	long rSize = (size_t) bufSize;

	// 마지막 '\n' 제거
	memset(strrchr(tMsgs, '\n'), '\0', 1);

	int mSize = snprintf((char *) bufPtr, rSize, "%s%c", tMsgs, DELIMITER);
	if(mSize < 0)
		return -1;

	rSize -= mSize;

	return (size_t) rSize;

}

// complete
size_t Text_Decode(char *tMsgs, uint8_t *inBuf, size_t bufSize) {

	int count = 0;
	int nextChar;

	while (count < bufSize) {
		nextChar = *inBuf++;

		tMsgs[count++] = nextChar;

		// End of field
		if (nextChar == DELIMITER) {
			// field delimiter 는 제거하고, '\n'로 대체
			memset(strrchr(tMsgs, '|'), '\n', 1);
			break;
		}

		// End of stream
		if(nextChar == '\n')
			return -1;
	}

	return count;
}
